package com.decent.ejfadmin.user.service.impl;

import com.decent.ejfadmin.common.bean.Announcement;
import com.decent.ejfadmin.common.bean.MessageBean;
import com.decent.ejfadmin.common.bean.Page;
import com.decent.ejfadmin.common.bean.SupUser;
import com.decent.ejfadmin.product.dao.ProductDao;
import com.decent.ejfadmin.product.response.dto.ModelPriceDto;
import com.decent.ejfadmin.user.dao.AnnouncementDao;
import com.decent.ejfadmin.user.dao.UserDao;
import com.decent.ejfadmin.user.service.UserAnnouncementService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 会员公告
 *
 * @author weicx
 * @date 2018/07/26
 */
@Service
@Slf4j
public class UserAnnouncementServiceImpl implements UserAnnouncementService {
    @Autowired
    private UserDao userDao;
    @Autowired
    private AnnouncementDao announcementDao;
    @Autowired
    private ProductDao productDao;

    /**
     * 获取目标会员ID
     *
     * @param readable
     * @return
     */
    private String genid(String readable) {
        List<String> userAccount = new ArrayList<String>();
        List<SupUser> allUserList = userDao.queryAllUserNotParam();
        for (SupUser user : allUserList) {
            userAccount.add(user.getUserId().toString());
        }
        String[] readble = readable.split(",");
        for (int i = 0; i < readble.length; i++) {
            userAccount.remove(readble[i]);
        }
        StringBuilder userStr = new StringBuilder();
        for (int i = 0; i < userAccount.size(); i++) {
            userStr.append(userAccount.get(i));
            if (i < userAccount.size() - 1) {
                userStr.append(",");
            }
        }
        return userStr.toString();
    }

    /**
     * 新增、修改公告时转换USERACCOUNT为USERID返回
     *
     * @param account account  会员编号
     * @return
     */
    private String getReadableId(String account) {
        String[] readble = account.split(",");
        StringBuffer sb = new StringBuffer(readble.length * 6);
        for (int i = 0; i < readble.length; i++) {
            SupUser u = userDao.querySupUsersByAccount(readble[i]);
            if (u == null) {
                continue;
            }
            sb.append(u.getUserId()).append(",");
        }
        return StringUtils.removeEnd(sb.toString(), ",");
    }


    /**
     * 新增公告
     *
     * @param announcement 公告类
     * @param state        所选会员是否可读：0可读  1不可读
     * @return
     */
    @Override
    public MessageBean addAnnouncement(Announcement announcement, Integer state) {
        getDbAnnouncement(announcement, state);
        announcement.setType(0);
        if (announcementDao.createNewAnnouncement(announcement) != 1) {
            return MessageBean.fail("新增会员公告失败");
        }
        return MessageBean.success();

    }

    /**
     * 修改公告
     *
     * @param announcement 公告实体类
     * @param state        所选会员是否可读：0可读  1不可读
     * @param operate      操作 0修改 1删除
     * @return
     */
    @Override
    public MessageBean updateAnnouncement(Announcement announcement, Integer state,
                                          Integer operate) {
        announcement.setDate(DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
        if (operate.equals(0)) {
            if (StringUtils.isBlank(announcement.getContent())) {
                return MessageBean.fail("请选择模板");
            }
            if (StringUtils.isBlank(announcement.getTitle())) {
                return MessageBean.fail("请输入标题");
            }
            getDbAnnouncement(announcement, state);
            if (announcementDao.modifyAnnouncement(announcement) != 1) {
                return MessageBean.fail("修改会员公告失败");
            }
        } else {
            if (announcementDao.deleteAnnouncement(announcement) != 1) {
                return MessageBean.fail("删除会员公告失败");
            }
        }
        return MessageBean.success();

    }

    /**
     * 得到可见会员和可见模板
     *
     * @param announcement 公告
     * @param state        所选会员是否可读：0可读  1不可读
     */
    private void getDbAnnouncement(Announcement announcement, Integer state) {
        if (StringUtils.isNotBlank(announcement.getReadable())) {
            announcement.setReadable(getReadableId(announcement.getReadable()));
            if (state == 1) {
                announcement.setReadable(genid(announcement.getReadable()));
            }
        } else {
            List<SupUser> users = userDao.queryAllUserNotParam();
            StringBuffer sb = new StringBuffer(users.size() * 6);
            for (SupUser supUser : users) {
                sb.append(supUser.getUserId()).append(",");
            }
            announcement.setReadable(StringUtils.removeEnd(sb.toString(), ","));
        }
        //全部模板
        if (StringUtils.isBlank(announcement.getModelId())) {
            StringBuilder models = new StringBuilder();
            List<ModelPriceDto> list = productDao.queryAllModel(true);
            for (ModelPriceDto modelPrice : list) {
                models.append(modelPrice.getId()).append(",");
            }
            announcement.setModelId(StringUtils.removeEnd(models.toString(), ","));
        }
    }

    /**
     * 分页查询公告
     *
     * @param page      分页组件
     * @param beginTime 起始时间
     * @param endTime   结束时间
     * @return MemberMessage
     */
    @Override
    public Page queryAnnouncement(Page page, String beginTime, String endTime) {
        int total = announcementDao.queryAnnouncementCount(beginTime, endTime);
        page.setTotal(total);
        if (total == 0) {
            page.setResultList(new ArrayList<>());
        } else {
            List<Announcement> list = announcementDao.queryAnnouncementPage(page.getBeginIndex(), page.getSize(), beginTime, endTime);
            for (Announcement announcement : list) {
                StringBuilder modelName = new StringBuilder();
                String[] modelIds = StringUtils.split(announcement.getModelId(), ",");
                for (String modelId : modelIds) {
                    ModelPriceDto modelPriceDto = productDao.queryModelById(Long.valueOf(modelId));
                    modelName.append(modelPriceDto.getModelName()).append(",");
                }
                announcement.setModelName(modelName.toString().substring(0, modelName.toString().length() - 1));
            }
            page.setResultList(list);
        }
        return page;
    }

    /**
     * 新增公告模板
     *
     * @param announcement 公告类
     * @param operator     操作 0：新增 1：修改
     * @return
     */
    @Override
    public MessageBean addAnnouncementModel(Announcement announcement, Integer operator) {
        if (Integer.valueOf(0).equals(operator)) {
            if (announcementDao.addAnnouncementModel(announcement) != 1) {
                return MessageBean.fail("新增公告模板失败");
            }
        } else {
            if (announcementDao.updateAnnouncementModel(announcement) != 1) {
                return MessageBean.fail("修改公告模板失败");
            }
        }
        return MessageBean.success();
    }

    /**
     * 查询公告模板
     *
     * @return
     */
    @Override
    public List getAnnouncementModel() {
        return announcementDao.getAnnouncementModel();
    }

    /**
     * 查询公告模板内容
     *
     * @return
     */
    @Override
    public String getAnnouncementModelContent(Integer id) {
        return announcementDao.getAnnouncementModelContent(id);
    }

    /**
     * 查看/修改公告时转换USERID为USERACCOUNT返回
     *
     * @param ids id   会员ID
     * @return
     */
    @Override
    public String getReadableAccount(String ids) {
        String[] split = ids.split(",");
        StringBuffer convert = new StringBuffer(split.length * 5);
        for (int i = 0; i < split.length; i++) {
            try {
                String userId = split[i];
                SupUser user = userDao.queryUserById(Long.parseLong(userId));
                if (user != null && StringUtils.isNotBlank(user.getAccount())) {
                    convert.append(user.getAccount()).append(",");
                }
            } catch (NumberFormatException e) {
                log.warn("类型转换异常", e);
                continue;
            }
        }
        return StringUtils.removeEnd(convert.toString(), ",");
    }

    /**
     * 查询公告列表
     *
     * @param id 公告Id
     * @return 公告信息
     */
    @Override
    public Announcement queryAnnouncementById(Integer id) {
        return announcementDao.queryAnnouncementById(id);
    }
}
